package br.com.ordersys.web;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import br.com.ordersys.framework.db.DBSessionManager;
import br.com.ordersys.framework.db.IDBSession;
import br.com.ordersys.framework.restlayer.RestLayerRequestAttributes;
import br.com.ordersys.framework.restlayer.auth.AuthenticationData;
import br.com.ordersys.web.data.UsuarioVO;

@Controller
// @RequestMapping("/flow")
public class FlowController {
	@RequestMapping(value = "/{page}.page", method = RequestMethod.GET)
	public String gotoPage(@PathVariable("page") String page, ModelMap model,HttpSession session, HttpServletRequest req) {
		AuthenticationData ad = (AuthenticationData) session.getAttribute(AuthenticationData.class.getName());

		if(ad != null){
			model.addAttribute("tenantId", ad.getTenantID());
			model.addAttribute("userId", ad.getUserID());
			model.addAttribute("userName", ad.getDisplayName());
			model.addAttribute("userEmail", ad.getEmail());
		}else{
			model.addAttribute("tenantId", req.getAttribute(RestLayerRequestAttributes.TENANT_ID));
		}
		
		return String.format("forward:/%s.jsp",page);
	}
	
	@RequestMapping(value = "/pswreset/{id}", method = RequestMethod.GET)
	public String passwordReset(@PathVariable("id") String id, ModelMap model,HttpSession session, HttpServletRequest req) {
		model.addAttribute("tenantId", req.getAttribute(RestLayerRequestAttributes.TENANT_ID));
		model.addAttribute("resetId", id);
		
		return "forward:/PasswordReset.jsp";
	}

	@RequestMapping(value = "/Logout", method = RequestMethod.GET)
	public String logout(ModelMap model,HttpSession session,HttpServletRequest req) {
		model.addAttribute("tenantId", req.getAttribute(RestLayerRequestAttributes.TENANT_ID));
		
		session.invalidate();
		
		return "forward:/Login.jsp";
	}
	
	@RequestMapping(value = "/afterlogin", method = RequestMethod.POST)
	public String afterLogin() {
		//return "redirect:/MainWindow.page";
		return null;
	}

	
	@RequestMapping(value = "/img/{type}/{id}", method = RequestMethod.GET)
	public void getImage(OutputStream out, HttpServletResponse resp, HttpSession session, @PathVariable("type") String type, @PathVariable("id") String id, ModelMap model) {

		try {
			AuthenticationData ad = (AuthenticationData) session.getAttribute(AuthenticationData.class.getName());

			ad.registry();

			if ("user".equals(type)) {
				byte[] vb = findUserImage(Integer.parseInt(id));

				if (vb != null && vb.length > 0) {
					resp.setContentType("image/png");
					out.write(vb);
					out.flush();
				}else{
					resp.setStatus(404);
				}
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			AuthenticationData.unregistryCurrent();
		}
	}

	private void getResourceFromContext(ServletContext servletContext, String name, OutputStream out) throws Exception {
		URL img = servletContext.getResource(name);
		
		if(img == null){
			return;
		}
		
		InputStream in = img.openStream();
		
		byte[] vb = new byte[512];

		int readen = 0;
		
		while( (readen = in.read(vb)) > -1){
			out.write(vb, 0, readen);
		}
	}

	private byte[] findUserImage(int userId) {
		IDBSession dbSession = null;
		try {
			dbSession = DBSessionManager.open();

			UsuarioVO usuVO = dbSession.findByPK(UsuarioVO.class, userId);
			return usuVO.asBlob("FOTO");
		} finally {
			DBSessionManager.close(dbSession);
		}
	}

}
